package com.aitaoxue.palx.base;

import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import android.os.AsyncTask;
import android.util.Log;

import com.aitaoxue.palx.bean.ListEntity;
import com.aitaoxue.palx.util.TDevice;
import com.loopj.android.http.AsyncHttpResponseHandler;

public abstract class NoCacheBaseListFragment extends BaseListFragment {
	private static final String TAG = NoCacheBaseListFragment.class
			.getSimpleName();

	private ParserTask mParserTask;

	protected void requestData(boolean refresh, Map<String, String> map) {
		Log.d(TAG, "开始查询");
		if (TDevice.hasInternet()) {
			sendRequestData(map);
		} else {
			executeOnLoadDataError(null);
			executeOnLoadFinish();
		}
	}

	// 不进行缓存
	protected AsyncHttpResponseHandler mCacheHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseBytes) {
			if (isAdded()) {
				if (mState == STATE_REFRESH) {
					onRefreshNetworkSuccess();
				}
				Log.d(TAG, "开始解析");
				executeParserTask(responseBytes);
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			if (isAdded()) {
				executeOnLoadDataError(null);
				executeOnLoadFinish();
			}
		}
	};

	private void executeParserTask(byte[] data) {
		cancelParserTask();
		mParserTask = new ParserTask(data);
		mParserTask.execute();
	}

	private void cancelParserTask() {
		if (mParserTask != null) {
			mParserTask.cancel(true);
			mParserTask = null;
		}
	}

	class ParserTask extends AsyncTask<Void, Void, String> {

		private byte[] reponseData;
		private boolean parserError;
		private List<?> list;

		public ParserTask(byte[] data) {
			Log.d(TAG, "构造方法");
			this.reponseData = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			Log.d(TAG, "doInBackground");
			try {
				ListEntity data = parseList(reponseData);
				list = data.getList();
			} catch (Exception e) {
				e.printStackTrace();
				parserError = true;
			}
			
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			Log.d(TAG, "onPostExecute");
			super.onPostExecute(result);
			if (parserError) {
				executeOnLoadDataError(null);
				executeOnLoadFinish();
			} else {
				Log.d(TAG, "success");
				executeOnLoadDataSuccess(list);
				executeOnLoadFinish();
			}
		}
	}

	@Override
	public void onDestroy() {
		cancelParserTask();
		super.onDestroy();
	}

}
